<template>
  <div>
    <div class="text-right" v-if="hasContract">
      <el-button class="mb-2" @click="handleView">查看合同</el-button>
      <el-button
        :loading="refuseLoading"
        class="float-right mr-2"
        @click="getRefush()"
        icon="el-icon-refresh"
      >
        刷新
      </el-button>
    </div>
    <div class="text-muted border rounded bg-light p-3 mb-3">
      委托合同信息处理说明:
      <div class="font-weight-bold">
        若已添加的反担保合同包含委托合同里面的内容，修改委托合同后需重新编辑一下反担保合同。
      </div>
      <!-- <div class="font-weight-bold">重做合同省农担重新发起合同审批，审批结束后加盖公章</div> -->
    </div>
    <el-form :model="related" label-position="left" size="small" label-width="150px">
      <el-form-item label="是否有共同借款人">
        <span v-if="isView">{{ { 0: '否', 1: '是' }[related.is_comm_loan] }}</span>
        <template v-else>
          <el-radio v-model="related.is_comm_loan" label="1">是</el-radio>
          <el-radio v-model="related.is_comm_loan" label="0">否</el-radio>
        </template>
      </el-form-item>
      <template v-if="+related.is_comm_loan === 1">
        <el-form-item label="共同借款人">
          <el-button size="mini" @click="addPerson" v-if="!isView">
            <i class="fa fa-plus"></i>
            新增共同借款人
          </el-button>
          <table
            style="line-height: 1.2rem"
            class="table table-bordered table-sm bg-white table-vertical-middle text-center"
          >
            <colgroup>
              <col width="12%" />
              <col width="15%" />
              <col width="12%" />
              <col width="16%" />
              <col width="20%" />
              <col width="15%" />
              <col width="10%" />
            </colgroup>
            <tr>
              <td>类型</td>
              <td>主体名称</td>
              <td>法人名字</td>
              <td>联系电话</td>
              <td>证件号</td>
              <td>地址</td>
              <td v-if="!isView">操作</td>
            </tr>
            <tr v-for="(p, index) of personData" :key="index">
              <td>{{ enumEntityType[p.com_person_type] }}</td>
              <td>{{ p.person_name }}</td>
              <td>{{ +p.com_person_type === 1 ? p.person_name_corp : '-' }}</td>
              <td>{{ p.person_phone }}</td>
              <td>{{ p.cert_no }}</td>
              <td>{{ p.person_address }}</td>
              <td v-if="!isView">
                <el-button type="text" @click="addPerson(p, index)">
                  <i class="fa fa-edit"></i>
                </el-button>
                <el-button type="text" @click="deletePerson(index)">
                  <i class="fa fa-trash text-danger"></i>
                </el-button>
              </td>
            </tr>
            <tr v-if="!personData.length">
              <td :colspan="isView ? 6 : 7" class="text-muted">请先新增共同借款人</td>
            </tr>
          </table>
        </el-form-item>
      </template>
    </el-form>
    <table class="table table-bordered table-vertical-middle" v-loading="loading">
      <tr>
        <td class="text-center font-weight-bold" width="4%" :rowspan="15">委托担保合同</td>
        <td class="td-label" width="16%">贷款主体</td>
        <td width="36%">{{ relatedData.customer_name || '-' }}</td>
        <td class="td-label" width="12%">客户类型</td>
        <td width="32%">{{ relatedData.org_class_name || '-' }}</td>
      </tr>
      <tr>
        <td class="td-label">联系人</td>
        <td>{{ relatedData.corp_name }}</td>
        <td class="td-label">
          <i class="fa fa-times text-danger" v-if="!checkMobile(contract.entrust_entity_phone)"></i>
          联系电话
        </td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.entrust_entity_phone || '-' }}</span>
          <input
            v-else
            class="form-control"
            placeholder="联系电话"
            v-model="contract.entrust_entity_phone"
          />
        </td>
      </tr>
      <tr>
        <td class="td-label">地址</td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.entrust_entity_address || '-' }}</span>
          <input
            v-else
            class="form-control"
            placeholder="请填写客户地址"
            v-model="contract.entrust_entity_address"
          />
        </td>
        <!-- registerData.bank_name || relatedData.bank_name -->
        <td class="td-label">放款银行名称</td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.bank_name || '-' }}</span>
          <input
            v-else
            class="form-control"
            placeholder="请填写放款银行名称"
            v-model="contract.bank_name"
          />
        </td>
      </tr>
      <tr>
        <td class="td-label">受托人</td>
        <td>
          {{ contract.accept_entrust_entity_name }}
          <!-- <span v-if="isView">{{ contract.accept_entrust_entity_name }}</span>
          <c-select
            v-else
            v-loading="agencyLoading"
            :options="agencies"
            :props="{ value: 'client_id', label: 'org_name' }"
            v-model="contract.gua_org_id"
            @change="handleAgencySelect"
            class="w-100"
          ></c-select> -->
        </td>
        <td class="td-label">受托人地址</td>
        <td>{{ contract.accept_entrust_entity_address }}</td>
      </tr>
      <tr>
        <td class="td-label">
          联合担保协议签订时间
          <div class="text-muted" v-if="isUnion">(非必填)</div>
        </td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.join_date || '-' }}</span>
          <el-date-picker
            v-else
            v-model="contract.join_date"
            type="date"
            placeholder="联合担保协议签订时间"
            class="w-100 start-date-pick"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </td>
        <td class="td-label">
          联合担保协议编号
          <div class="text-muted" v-if="isUnion">(非必填)</div>
        </td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.join_no || '-' }}</span>
          <el-input
            v-else
            type="textarea"
            class="w-100"
            placeholder="合同编号"
            v-model="contract.join_no"
          ></el-input>
        </td>
      </tr>
      <tr>
        <td class="td-label">保证合同签订银行名称</td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.entrust_bank_name || '-' }}</span>
          <el-input
            v-else
            type="textarea"
            class="w-100"
            placeholder="请填写保证合同签订银行名称"
            v-model="contract.entrust_bank_name"
          ></el-input>
        </td>
        <td class="td-label">贷款利率</td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.load_rate || '-' }}%</span>
          <div class="d-flex align-items-center" v-else>
            <input
              v-input-number="{ min: 0, max: 100, fixed: 2 }"
              class="form-control"
              placeholder="请填写"
              v-model="contract.load_rate"
            />
            <span class="px-3 text-muted">%</span>
          </div>
        </td>
      </tr>
      <tr>
        <td class="td-label">借款合同</td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.loan_contract_no || '-' }}</span>
          <div class="d-flex align-items-center" v-else>
            <el-input
              type="textarea"
              rows="3"
              class="w-100"
              placeholder="合同编号"
              v-model="contract.loan_contract_no"
            ></el-input>
            <el-date-picker
              v-model="contract.contract_date"
              type="date"
              placeholder="合同签订时间"
              style="width: 250px"
              class="start-date-pick"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
        </td>
        <td class="td-label">授信/借款金额</td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.reply_funds || '-' }}万元</span>
          <div class="d-flex align-items-center" v-else>
            <input
              v-input-number="{ min: 0, fixed: 2 }"
              class="form-control"
              @change="setGuaFee"
              placeholder="请填写"
              v-model="contract.reply_funds"
            />
            <div class="px-3 text-muted" style="min-width: 60px">万元</div>
          </div>
        </td>
      </tr>
      <tr>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.ensure_contract_name || '保证合同' }}</span>
          <c-select
            v-else
            class="w-100"
            :props="{ label: 'label', value: 'label' }"
            :options="[
              {
                label: '保证合同',
              },
              {
                label: '银担合作协议',
              },
            ]"
            v-model="contract.ensure_contract_name"
            @change="onTip"
          ></c-select>
        </td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.ensure_contract_no || '-' }}</span>
          <div v-else>
            <el-input
              type="textarea"
              class="w-100"
              placeholder="请填写编号"
              v-model="contract.ensure_contract_no"
            ></el-input>
          </div>
        </td>
        <td class="td-label">贷款期限</td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.load_years || '-' }}月</span>
          <div class="d-flex align-items-center" v-else>
            <input
              class="form-control"
              @change="setGuaFee"
              placeholder="请填写"
              v-model="contract.load_years"
              v-input-number="{ min: 0, max: 120, fixed: 0 }"
            />
            <span class="px-3 text-muted">月</span>
          </div>
        </td>
        <!-- <td>{{ contract.load_years || '-' }} 月</td> -->
      </tr>
      <tr>
        <td class="td-label">贷款品种</td>
        <td :class="tdClass">
          <span v-if="isView">{{ debitType[contract.loan_varieties] || '-' }}</span>
          <div v-else>
            <c-select
              :options="debitType"
              class="w-100"
              placeholder="选择贷款品种"
              v-model="contract.loan_varieties"
            ></c-select>
          </div>
        </td>
        <td class="td-label">担保费率</td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.gua_rate || '-' }}%</span>
          <div class="d-flex align-items-center" v-else>
            <input
              v-input-number="{ min: 0, max: 100, fixed: 2 }"
              class="form-control"
              @change="setGuaFee"
              placeholder="请填写"
              v-model="contract.gua_rate"
            />
            <span class="px-3 text-muted">%</span>
          </div>
        </td>
      </tr>
      <tr>
        <td class="td-label">保费收取方式</td>
        <td :class="tdClass">
          <span v-if="isView">
            {{ enumGuaFundsType[contract.gua_fee_coll_type] }}
          </span>
          <c-select
            v-else
            class="w-100"
            :options="enumGuaFundsType"
            v-model="contract.gua_fee_coll_type"
            placeholder="保费收取方式"
          ></c-select>
        </td>
        <td class="td-label">担保费</td>
        <td :class="tdClass">
          <!-- {{ contract.gua_fee || '-' }} 元 -->
          <span v-if="isView">
            每年担保费：{{ contract.gua_fee_per || '-' }}元 合计：{{ contract.gua_fee || '-' }}元
          </span>
          <div class="d-flex align-items-center" v-else>
            <el-input
              v-model="contract.gua_fee_per"
              v-input-number="{ min: 0, fixed: 2 }"
              placeholder="每年收取担保费"
            ></el-input>
            元
            <el-input
              v-model="contract.gua_fee"
              v-input-number="{ min: 0, fixed: 2 }"
              placeholder="请输入担保费合计"
            ></el-input>
            元
          </div>
        </td>
      </tr>
      <!-- <tr>
        <td class="td-label">起始日期</td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.load_date || '-' }}</span>
          <el-date-picker
            v-else
            v-model="contract.load_date"
            type="date"
            placeholder="起始日期"
            class="w-100 start-date-pick"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </td>
        <td class="td-label">结束日期</td>
        <td :class="tdClass">
          <span v-if="isView">{{ contract.load_end_date || '-' }}</span>
          <el-date-picker
            v-else
            v-model="contract.load_end_date"
            type="date"
            placeholder="结束日期"
            class="w-100 start-date-pick"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </td>
      </tr> -->
      <tr>
        <td class="td-label">贷款用途</td>
        <td colspan="3" :class="tdClass">
          <div v-if="isView">{{ contract.funds_use_dir || '' }}</div>
          <el-input v-else placeholder="贷款用途" v-model="contract.funds_use_dir"></el-input>
        </td>
      </tr>
      <tr>
        <td class="td-label">还款方式</td>
        <td colspan="3" :class="tdClass">
          <div v-if="isView">{{ contract.repay_method || '' }}</div>
          <el-input
            v-else
            type="textarea"
            placeholder="还款方式"
            :rows="5"
            v-model="contract.repay_method"
          ></el-input>
        </td>
      </tr>
      <tr>
        <td class="td-label">反担保措施</td>
        <td colspan="3" :class="tdClass">
          <span v-if="isView">{{ contract.gua_method_des }}</span>
          <el-input
            v-else
            type="textarea"
            placeholder="反担保措施"
            :rows="5"
            v-model="contract.gua_method_des"
          ></el-input>
        </td>
      </tr>
      <tr>
        <td class="td-label">合同设置</td>
        <td colspan="3" :class="tdClass">
          <span v-if="isView">
            本合同一式{{ contract.num_copes || '-' }}份，双方各执{{ contract.num_copes_per || '-' }}
            份，办理相关法律手续所需文本按需设置。
          </span>
          <div v-else class="d-flex align-items-center px-2">
            本合同一式
            <el-input
              style="width: 5rem"
              v-model="contract.num_copes_lower"
              placeholder="共计"
              v-input-number="{ min: 0, fixed: 0 }"
            ></el-input>
            份，双方各执
            <el-input
              style="width: 5rem"
              v-model="contract.num_copes_per_lower"
              placeholder="各执"
              v-input-number="{ min: 0, fixed: 0 }"
            ></el-input>
            份，办理相关法律手续所需文本按需设置。
          </div>
        </td>
      </tr>
    </table>
    <div v-if="(isRedo || isSYSTEM) && !isView">
      <c-select
        :options="{
          0: '不盖章(客户线下签约时选择)',
          1: '加盖公章',
        }"
        :number-key="true"
        v-model="signStatus"
      ></c-select>
    </div>
    <div class="text-center py-4" v-if="!isView">
      <el-button type="primary" class="btn-long" :loading="submitLoading" @click="submit">
        {{ hasContract ? '修改' : '提交' }}委托合同
      </el-button>
      <!-- <el-button class="btn-long"
                  :loading="submitLoading"></el-button> -->
    </div>

    <el-dialog
      top="30px"
      width="900px"
      append-to-body
      :close-on-click-modal="false"
      :before-close="beforeClose"
      :visible.sync="entrustView"
    >
      <pdf-view :contract-id="contractId" :view-mode="true" :query-id="queryId"></pdf-view>
    </el-dialog>
    <common-person
      :visible.sync="editCommonVisible"
      :form-data="editCommonForm"
      @back="setPerson"
      :attach="[]"
    ></common-person>
  </div>
</template>

<script>
import { enumCompanyType } from '@/gov/plugins/enum'
import { mapGetters } from 'vuex'
import { nzhToMoney, mul, sub, nzhToNum } from '@vimi/utils-tool'
import { enumGuaFundsType } from '@/credit/views/county/unionProvince/components/projectApprove/index'
import PdfView from '@/credit/views/county/unionProvince/components/PdfView'
import { enumEntityType } from '@/credit/views/county/unionProvince/components/ContractGuardMortgage'
import CommonPerson from '@/credit/views/city/program/ocr/CommonPerson'
import { checkMobile } from '@/common/plugins/validator'
export default {
  props: {
    viewMode: {
      type: Boolean,
      default: false,
    },
    relatedData: {
      type: Object,
      default: () => ({}),
    },
    isRedo: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    PdfView,
    CommonPerson,
  },
  data() {
    return {
      checkMobile,
      enumEntityType,
      enumGuaFundsType,
      enumCompanyType,
      loading: false,
      debitType: {
        1: '流贷',
        2: '固贷',
        3: '其他',
      },
      agencyLoading: false,
      submitLoading: false,
      contract: {
        gua_org_id: '',
        accept_entrust_entity_name: '',
      },
      agencies: [],
      unionLetter: {},
      registerData: {}, // 审批秘书登记结果
      entrustView: false,
      refuseLoading: false,
      related: {
        is_comm_loan: '',
      },
      personTable: 'comm_loan_person',
      personData: [],
      mainPerson: {},
      bolbUrl: {},
      attachs: {},
      editCommonVisible: false,
      editCommonForm: {},
      editIndex: -1,
      signStatus: 1,

      noticeData: {},
    }
  },
  computed: {
    ...mapGetters(['entrustContract', 'org', 'clientId', 'user']),
    isUnion() {
      return this.user?.scopeArr?.includes('dirGuaPro') ?? false
    },
    contractId() {
      return this.entrustContract.doc_id
    },
    isView() {
      // return false
      return this.viewMode || (+this.entrustContract.sign_status > 0 && this.entrustContract.doc_id)
    },
    isSYSTEM() {
      // 系统后台重做合同
      return this.org.orgClass === 'org_credit_sys'
    },
    tdClass() {
      return this.isView ? '' : 'input-td'
    },
    hasContract() {
      return !!this.entrustContract.entrust_contract_id
    },
    contracEditId() {
      return this.entrustContract.entrust_contract_id
    },
    queryId() {
      return this.relatedData.customer_related_id
    },
    orgName() {
      return this.org.orgName
    },
  },
  watch: {
    queryId: {
      handler: function () {
        if (!this.queryId) {
          return
        }
        this.related.is_comm_loan = this.relatedData.is_comm_loan || '0'
        this.loading = true
        // 获取调查审批秘书登记内容及上一次委托合同的联合担保协议编号及时间,组织信息内
        Promise.all([
          this.getRegisterData(),
          this.getUnionLetter(),
          this.getPerson(),
          this.getLoanNotice(),
          this.$store.dispatch('getEntrustContract', this.queryId),
        ])
          .then(() => {
            this.initContractByExist()
            if (this.agencies.length) {
              this.setContractAcceptAgency(this.agencies[0])
            } else {
              this.getAgency()
            }
          })
          .finally(() => {
            this.loading = false
          })
      },
      immediate: true,
    },
  },
  created() {},
  methods: {
    onTip() {
      if (this.contract.ensure_contract_name !== '保证合同') {
        this.$message({
          showClose: true,
          message:
            '此文案仅用于放款通知书，联保函、委托合同及反担保合同内，文案一直为保证合同，谨慎选择',
          type: 'warning',
          duration: 0,
        })
      }
    },
    // 重做合同时如果有放款通知书需同步修改放款通知书内容
    getLoanNotice() {
      return this.$api
        .getData(
          this.$serviceName,
          'loan_notice',
          { 'customer_related_id.eq': this.queryId },
          { create_time: 'desc' }
        )
        .then(res => {
          this.noticeData = res?.data?.[0] ?? {}
        })
    },
    upDateNotice() {
      if (!this.noticeData.loan_notice_id) {
        return
      }
      this.$api.updateData(this.$serviceName, 'loan_notice', this.noticeData.loan_notice_id, {
        apply_funds: this.contract.reply_funds,
        apply_funds_capital: this.contract.reply_funds_capital,
        ensure_contract_no: this.contract.ensure_contract_no,
        ensure_contract_name: this.contract.ensure_contract_name || '保证合同',
        entrust_gua_no: this.contract.entrust_contract_cno,
        load_years: this.contract.load_years,
        loan_contract_no: this.contract.loan_contract_no,
        bank_name: this.contract.bank_name,
      })
    },
    setPerson(person) {
      if (this.editIndex === -1) {
        this.personData.push(person)
      } else {
        this.personData[this.editIndex] = { ...person }
      }
    },
    addPerson(row = {}, index = -1) {
      this.editCommonVisible = true
      this.editCommonForm = { ...row }
      this.editIndex = index
    },
    deletePerson(index) {
      if (this.personData.length < 2) {
        return this.$message.warning('最少需添加一个共同借款人')
      }
      this.personData.splice(index, 1)
    },
    getPerson() {
      return this.$api
        .getData(
          this.$serviceName,
          this.personTable,
          { 'customer_related_id.eq': this.queryId },
          { is_main: 'desc' }
        )
        .then(res => {
          const data = res?.data ?? []
          this.personData = data.filter(item => +item.is_main === 0)
          this.mainPerson = data.find(item => +item.is_main === 1) || {}
        })
    },
    getRefush() {
      this.refuseLoading = true
      this.$store.dispatch('getEntrustContract', this.queryId).finally(() => {
        this.refuseLoading = false
      })
    },
    setGuaFee() {
      const year = Math.ceil(this.contract.load_years / 12)
      this.contract.gua_fee_per =
        Math.round(+this.contract.reply_funds * this.contract.gua_rate * 10000) / 100
      this.contract.gua_fee = this.contract.gua_fee_per * year
    },
    beforeClose() {
      this.entrustView = false
    },
    handleView() {
      this.entrustView = true
    },
    getRegisterData() {
      return this.$api
        .getData(
          this.$serviceName,
          'project_approval_register',
          {
            'customer_related_id.eq': this.queryId,
          },
          { approval_register_type: 'desc' }
        )
        .then(res => {
          this.registerData = res?.data?.[0] ?? {}
        })
    },
    submit() {
      if (!this.queryId) {
        return
      }
      if (!this.validator()) return
      this.contract.reply_funds_yuan = +this.contract.reply_funds * 10000
      this.contract.reply_funds_capital = nzhToMoney(this.contract.reply_funds_yuan)
      this.contract.gua_fee_total_capital = nzhToMoney(+this.contract.gua_fee)
      // const yearCapital = this.contract.gua_fee /
      this.contract.gua_fee_capital = nzhToMoney(+this.contract.gua_fee_per)
      this.contract.sign_date = this.$utils.dateFormat(new Date(), 'yyyy年MM月dd日')
      this.contract.num_copes_per = this.contract.num_copes_per_lower
        ? nzhToNum(this.contract.num_copes_per_lower)
        : ''
      this.contract.num_copes = this.contract.num_copes_lower
        ? nzhToNum(this.contract.num_copes_lower)
        : ''

      if (+this.related.is_comm_loan === 1 && this.personData.length < 1) {
        return this.$message.error('至少输入一个共同借款主体')
      }
      if (!checkMobile(this.contract.entrust_entity_phone)) {
        return this.$message.warning('贷款主体手机号错误')
      }

      let personData = []
      if (+this.related.is_comm_loan === 1) {
        personData = this.personData.map(item => {
          item.customer_related_id = this.queryId
          return item
        })
      }

      const mainPerson = {
        ...this.mainPerson,
        com_person_type: +this.relatedData.customer_type === 1 ? 1 : 2,
        person_name: this.relatedData.customer_name,
        is_main: 1,
        cert_no:
          +this.relatedData.customer_type === 1
            ? this.relatedData.register_no
            : this.relatedData.lender_idcard,
        person_address: this.contract.entrust_entity_address,
        person_phone: this.contract.entrust_entity_phone,
      }
      personData.push(mainPerson)
      const updateformData = {
        masterTableInfo: JSON.stringify({
          customer_related_id: this.queryId,
          reply_funds: this.contract.reply_funds,
          months: this.contract.load_years,
          load_date: this.contract.load_date || null,
          load_end_date: this.contract.load_end_date || null,
          is_comm_loan: this.related.is_comm_loan,
          mobile_no: mainPerson.person_phone,
        }),
        masterTableName: 'customer_related',
        slaveTableInfo: JSON.stringify(personData),
        slaveTableName: this.personTable,
      }
      this.submitLoading = true
      this.$api
        .relatedUpdate(this.$serviceName, updateformData)
        .then(() => {
          if (this.hasContract) {
            this.putData()
          } else {
            this.postData()
          }
          this.getPerson()
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '提交失败，请重试！')
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    getUnionLetter() {
      const params = {
        'ele_letter_type.eq': 2,
        'customer_related_id.eq': this.queryId,
      }
      const tableName = 'ele_letter_info'
      return this.$api
        .getData(this.$serviceName, tableName, params, { create_time: 'desc' })
        .then(res => {
          this.unionLetter = res?.data?.[0] ?? {}
        })
    },
    updateUnionLetter() {
      const guaRate = sub(100, this.relatedData.bank_risk_rate)
      const data = {
        customer_related_id: this.queryId,
        ele_letter_type: 2,
        letter_date: this.$utils.dateFormat(new Date(), 'yyyy-MM-dd'),
        gua_org_id: this.isUnion
          ? this.relatedData.gua_service_id || this.relatedData.recommend_service
          : this.clientId,
        gua_company: this.isUnion
          ? this.relatedData.gua_service_name || this.relatedData.recommend_service_name
          : this.relatedData.service_name,
        sign_date: this.$utils.dateFormat(new Date(), 'yyyy年MM月dd日'),
        customer_name: this.relatedData.customer_name,
        gua_org_name_short: this.org.orgNameShort,
        wt_no: this.entrustContract.entrust_contract_cno,
        bank_name: this.contract.bank_name,
        entrust_bank_name: this.contract.entrust_bank_name,
        ensure_contract_no: this.contract.ensure_contract_no,
        //  ensure_contract_name: this.contract.ensure_contract_name || '保证合同',
        loan_contract_no: this.contract.loan_contract_no,
        apply_funds: this.contract.reply_funds,
        apply_funds_capital: nzhToMoney(this.contract.reply_funds * 10000),
        join_date: this.$utils.dateFormat(this.contract.join_date, 'yyyy年MM月dd日'),
        join_no: this.contract.join_no,
        bear_rate_divide: Math.round((this.relatedData.join_risk_rate_qx / guaRate) * 10000) / 100,
        bear_rate: guaRate,
        total_risk_rate: this.relatedData.join_risk_rate_qx,
      }
      if (!this.unionLetter.ele_letter_info_id) {
        this.$api
          .addData(this.$serviceName, 'ele_letter_info', data)
          .then(() => {
            this.getUnionLetter()
            this.$emit('letter', true)
          })
          .catch(err => {
            this.$message.error(err?.data?.error_description || '生成联保函失败！')
          })
      } else {
        this.$api
          .updateData(
            this.$serviceName,
            'ele_letter_info',
            this.unionLetter.ele_letter_info_id,
            data
          )
          .then(() => {
            this.$emit('letter', true) // 更新联保函
          })
      }
    },
    async putData() {
      this.submitLoading = true
      const keys = [
        'accept_entrust_entity_address',
        'accept_entrust_entity_corp',
        'accept_entrust_entity_name',
        'accept_entrust_entity_phone',
        'approval_fee',
        'bank_name',
        'customer_related_id',
        'ensure_contract_no',
        'ensure_contract_name',
        'entrust_entity_address',
        'entrust_entity_cert_no',
        'entrust_entity_name',
        'entrust_entity_phone',
        'funds_use_dir',
        'gua_fee',
        'gua_fee_per',
        'gua_fee_capital',
        'gua_fee_total_capital',
        'gua_method_des',
        'gua_org_code',
        'gua_org_id',
        'gua_org_name_short',
        'gua_rate',
        'load_date',
        'load_end_date',
        'load_rate',
        'load_years',
        'loan_contract_no',
        'loan_varieties',
        'repay_method',
        'reply_funds',
        'reply_funds_capital',
        'sign_date',
        'entrust_entity_corp',
        'join_date',
        'join_no',
        'contract_date',
        'reply_funds_yuan',
        'num_copes_per',
        'num_copes',
        'num_copes_per_lower',
        'num_copes_lower',
        'entrust_bank_name',
        'bank_name',
      ]
      const data = {}
      keys.forEach(key => {
        data[key] = this.contract[key]
      })
      data.ensure_contract_name = data.ensure_contract_name || '保证合同'
      if (this.isSYSTEM || this.isRedo) {
        //系统后台重做重签合同
        data.re_sign_type = 1
        data.sign_status = this.signStatus
      }
      const [res] = await this.$utils.promise(
        this.$api.updateData(this.$serviceName, 'entrust_contract', this.contracEditId, data)
      )
      this.submitLoading = false
      if (res) {
        this.$message.success('修改委托合同成功')
        this.upDateNotice()
        this.$store.dispatch('getEntrustContract')
        this.$store.dispatch('getEntrustContract', this.queryId).finally(() => {
          this.updateUnionLetter()
          this.$store.dispatch('getOrg')
        })
        this.$emit('success', 0)
        // this.$emit('close', false)
      } else {
        this.$message.error('修改委托合同失败')
      }
    },
    async postData() {
      this.submitLoading = true
      const [res] = await this.$utils.promise(
        this.$api.addData(this.$serviceName, 'entrust_contract', {
          ...this.contract,
          ensure_contract_name: this.contract.ensure_contract_name || '保证合同',
        })
      )
      this.submitLoading = false
      if (res) {
        this.$message.success('提交委托合同成功')
        this.$store.dispatch('getEntrustContract')
        this.$store.dispatch('getEntrustContract', this.queryId).finally(() => {
          this.$store.dispatch('getOrg')
          this.updateUnionLetter()
        })
        this.$emit('nextTag', true)
        this.$emit('success', 1)
      } else {
        this.$message.error('提交委托合同失败')
      }
    },
    validator() {
      const otherValid =
        this.isUnion || this.isSYSTEM
          ? {}
          : { join_date: '请选择联合担保协议签订时间', join_no: '请填写联合担保协议编号' }
      const enumValid = {
        gua_org_id: '请选择受托人',
        ...otherValid,
        load_rate: '请填写贷款利率',
        loan_contract_no: '请填写授信合同/借款编号',
        contract_date: '请选择借款合同签订时间',
        reply_funds: '请填写授信/借款金额',
        ensure_contract_no: '请填写保证合同号',
        load_years: '请填写期限',
        loan_varieties: '请选择贷款品种',
        repay_method: '请输入还款方式',
        gua_rate: '请填写担保费率',
        gua_fee: '请填写担保费（总额）',
        // load_date: '请选择起始日期',
        // load_end_date: '请选择结束日期',
        entrust_bank_name: '请输入保证合同签订银行',
        num_copes_per_lower: '请输入合同份数',
        num_copes_lower: '请输入合同份数',
      }

      const keys = Object.keys(enumValid)
      for (const key of keys) {
        if (!this.contract[key]) {
          this.$message.error(enumValid[key])
          return false
        }
      }

      return true
    },
    initContractByExist() {
      if (this.hasContract) {
        this.contract = {
          ...this.entrustContract,
          entrust_entity_name: this.relatedData.customer_name,
          entrust_entity_cert_no: this.relatedData.register_no || this.relatedData.lender_idcard,
        }
      } else {
        this.initContractByRelated()
      }
    },
    async getAgency() {
      let params = {}
      params = {
        'orWhere.client_id.eq': [this.relatedData.recommend_service],
      }
      this.agencyLoading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, 'credit_select_view', params, {
          N1address_code: 'asc',
        })
      )
      this.agencyLoading = false

      this.agencies = res?.data ?? []

      this.setContractAcceptAgency(this.agencies[0])
    },
    handleAgencySelect(value) {
      const agency = this.agencies.find(item => item.client_id === value)
      this.setContractAcceptAgency(agency)
    },
    setContractAcceptAgency(agency) {
      if (!agency) return
      this.contract.gua_org_id = agency.client_id
      this.contract.accept_entrust_entity_name = agency.org_name
      this.contract.accept_entrust_entity_address = agency.address || ''
      this.contract.gua_org_code = agency.org_code
      this.contract.gua_org_name_short = agency.org_name_short
      this.contract.accept_entrust_entity_corp = agency.corp_name
      this.contract.accept_entrust_entity_phone = agency.phone_number
    },
    initContractByRelated() {
      this.contract = {
        gua_org_id: '',
        entrust_entity_name: this.relatedData.customer_name,
        entrust_entity_address: this.relatedData.address,
        entrust_entity_cert_no: this.relatedData.register_no || this.relatedData.lender_idcard,
        entrust_entity_phone: this.relatedData.mobile_no,
        entrust_entity_corp: this.relatedData.corp_name,
        bank_name: this.registerData.bank_name || this.relatedData.bank_name,
        load_rate: this.registerData.load_rate,
        funds_use_dir: this.registerData.funds_use_dir,
        reply_funds: this.registerData.res_funds || this.relatedData.apply_funds,
        load_years: this.registerData.res_months || this.relatedData.months,
        customer_related_id: this.relatedData.customer_related_id,
        gua_rate: this.registerData.gua_rate,
        approval_fee: this.registerData.approval_fee,
        load_date: this.relatedData.load_date || '',
        load_end_date: this.relatedData.load_end_date || '',
        gua_fee_coll_type: '1',
        gua_fee: this.registerData.gua_fee,
        gua_fee_per:
          Math.round(
            +(this.registerData.res_funds || '') * +(this.registerData.gua_rate || '') * 10000
          ) / 100,
        gua_method_des: this.registerData.gua_method_des,
        join_date: this.isUnion ? '' : this.org.joinDate,
        join_no: this.isUnion ? '' : this.org.joinNo,
        accept_entrust_entity_name: '',
        accept_entrust_entity_address: '',
        // bank_name: this.registerData.bank_name || this.relatedData.bank_name,
      }
    },
    guaFee(data) {
      let {
        gua_fee_coll_type: type = '',
        gua_rate: rate = '',
        load_years: months = '',
        reply_funds: funds = '',
      } = data
      type = +type
      rate = +rate * 1e-2
      funds = +funds * 1e4
      const year = Math.ceil(months / 12)
      if (type === 0 || rate === 0 || year === 0 || funds === 0) {
        return ''
      }
      if (type === 1) {
        return mul(funds, rate, year)
      }
      if (type === 2) {
        return mul(funds, rate)
      }
      return ''
    },
  },
}
</script>
<style lang="scss" scoped>
.table-vertical-middle td {
  vertical-align: middle;
}
.td-label {
  background-color: #f8f9fa;
  text-align: center;
}
.input-td {
  background-color: #ffffee;
}
</style>
